package router

import (
	"goadmin/api"
	"goadmin/conf"
	"goadmin/middleware"
	"goadmin/ws"
	"time"

	_ "goadmin/validate"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

var Routes *gin.Engine

func init() {
	if conf.App.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}
	Routes = gin.Default()
	Routes.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"}, // 或者更具体的域名
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		AllowOriginFunc: func(origin string) bool {
			return true // 可以根据实际情况进行调整
		},
		MaxAge: 12 * time.Hour,
	}))

	Routes.Static("/upload", "./upload")
	// ws
	{
		g := Routes.Group("/ws")
		{
			g.GET("", ws.Ws)
		}
	}
	// api
	apiG := Routes.Group("/api")
	{
		apiG.GET("/hello", api.Hello)
		// app
		{
			logged := apiG.Group("/apps").Use(middleware.Logged())
			{
				logged.GET("/config", api.AppGetConfig)
				logged.PUT("/captcha", api.AppChangeCaptchaEnable)
				logged.PUT("/register", api.AppChangeRegisterEnable)
			}
		}
		// captcha
		{
			g := apiG.Group("/captchas")
			{
				g.GET("", api.CaptchaGet)
			}
		}
		// session
		{
			g := apiG.Group("/sessions")
			{
				g.PUT("", api.SessionRefresh)
				g.DELETE("", api.SessionRemove)
			}
			notLogged := apiG.Group("/sessions").Use(middleware.NotLogged())
			{
				notLogged.POST("", api.SessionIssue)
			}
		}
		// user
		{
			// g := apiG.Group("/users")
			notLogged := apiG.Group("/users").Use(middleware.NotLogged())
			{
				notLogged.POST("", api.UserRegister)
			}
			logged := apiG.Group("/users").Use(middleware.Logged())
			{
				logged.GET("", api.UserList)
				logged.GET("/me", api.UserSelfInfo)
				logged.PUT("/me/password", api.UserChangePassword)
				logged.PUT("/me/avatar", api.UserChangeAvatar)
				logged.PUT("/me/info", api.UserChangeInfo)
				logged.POST("/batch_delete", api.UserBatchDel)
				needPathId := logged.Use(middleware.PathId())
				{
					needPathId.GET("/:id", api.UserInfo)
					needPathId.DELETE("/:id", api.UserDel)
				}
			}
		}
		// file
		{
			logged := apiG.Group("/files").Use(middleware.Logged())
			{
				logged.GET("", api.FileFindHash)
				logged.POST("", api.FileUpload)
			}
		}

	}
}
